package com.ad.pet.common.data.loader;

import android.app.Activity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;

import javax.inject.Inject;

/**
 * Created by z on.
 * Des:
 * Date: 2017/3/11
 */

public class ImageUriToPathLoader implements LoaderManager.LoaderCallbacks<Cursor> {

    Activity mActivity;
    private LoaderCallback<String> mCallback;

    @Inject
    public ImageUriToPathLoader(Activity activity) {
        mActivity = activity;
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        String[] proj = {MediaStore.Images.Media.DATA};
        CursorLoader loader = new CursorLoader(mActivity, Uri.parse(args.getString("uri")),
                proj, null, null, null);
        return loader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        if (data != null) {
            if (data.moveToFirst()) {
                int actual_image_column_index = data.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                String path = data.getString(actual_image_column_index);
                if (mCallback != null) mCallback.complete(path);
                data.close();
            }
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
    }

    public void setCallback(LoaderCallback<String> callback) {
        if (callback != null) {
            mCallback = callback;
        }
    }
}
